/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.gov.cemaden.smp.util;

import java.util.*;
import java.net.*;
import sun.jvmstat.monitor.*;
import sun.tools.jps.Arguments;

/**
 *
 * @author Simone Santos
 */
public class ScanPid {

    private List<String> pids;
    private HostIdentifier host;
    private MonitoredHost monitoredHost;

    public ScanPid() {
        pids = new ArrayList<String>();
        try {
            host = new HostIdentifier("localhost");
        } catch (URISyntaxException e) {
        }
    }

    public List<String> getPids() {
        return pids;
    }

    //scan caso tenha os args
    public void scan(String[] args) {
        Arguments arguments = null;
        try {
            arguments = new Arguments(args);
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
            Arguments.printUsage(System.err);
            return;
        }
        if (arguments.isHelp()) {
            Arguments.printUsage(System.out);
            System.exit(0);
        }
        System.out.println(arguments.hostId().getHost());
        host = arguments.hostId();
        scan();
    }

    //scan caso ja tenha o objeto HostIdentifier criado
    @SuppressWarnings("rawtypes")
    public void scan() {
        try {
            //conecta no host
            MonitoredHost monitoredHost = getMonitor();
            //pega as vms ativas
            Set jvms = monitoredHost.activeVms();

            for (Iterator j = jvms.iterator(); j.hasNext();) {

                int lvmid = ((Integer) j.next()).intValue();
                pids.add(String.valueOf(lvmid));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getNameByPID(String pid) throws MonitorException {

        MonitoredVm vm = null;
        String vmidString = "//" + pid + "?mode=r";

        try {
            VmIdentifier id = new VmIdentifier(vmidString);
            vm = getMonitor().getMonitoredVm(id, 0);
        } catch (Exception e) {
        }
        return MonitoredVmUtil.mainClass(vm, false);
    }

    private MonitoredHost getMonitor() throws MonitorException, URISyntaxException {
        if (monitoredHost == null) {
            monitoredHost = MonitoredHost.getMonitoredHost(host);
        }
        return monitoredHost;
    }
}